import api from "@/store/api/index.js";

import { getStoreListAsync, removeStore } from "@/store/slice/storeSlice.js";
import { Badge, Toast } from "antd-mobile";
import {
  LeftOutline,
  LikeOutline,
  MessageOutline,
  MoreOutline,
  StarOutline,
} from "antd-mobile-icons";
import React, { useEffect, useMemo } from "react";
import { useDispatch, useSelector } from "react-redux";
import SkeletonAgain from "../components/SkeletonAgain";
import { useGetNewsInfoQuery, useGetStoryExtraQuery } from "../store/api/Api";
import { setUserInfoAsync } from "../store/slice/baseSlice";
import "./Detail.less";

export default function Detail(props) {
  let { params, navigate, location } = props;
  const {
    data: result,
    isSuccess,
    isFetching,
  } = useGetNewsInfoQuery(params.id);
  let link;
  const {
    data: extraData,
    isSuccess: extraSuccess,
    isFetching: extraFetching,
  } = useGetStoryExtraQuery(params.id);
  // 样式
  const handleStyle = (result) => {
    let { css } = result;
    if (!Array.isArray(css)) return;
    css = css[0];
    if (!css) return;
    // 创建<Link>
    link = document.createElement("link");
    link.rel = "stylesheet";
    link.href = css;
    document.head.appendChild(link);
  };
  //创建大图
  const handleImage = (result) => {
    let imgPlaceHolder = document.querySelector(".img-place-holder");
    if (!imgPlaceHolder) return;
    // 创建大图
    let tempImg = new Image();
    tempImg.src = result.image;
    tempImg.onload = () => {
      imgPlaceHolder.appendChild(tempImg);
    };
    tempImg.onerror = () => {
      let parent = imgPlaceHolder.parentNode;
      parent.parentNode.removeChild(parent);
    };
  };
  useEffect(() => {
    if (isSuccess) {
      handleStyle(result);
      handleImage(result);
    }

    return () => {
      if (link) document.head.removeChild(link);
    };
  }, [isSuccess]);
  // ======================登录收藏的逻辑
  const dispatch = useDispatch();
  const { userInfo } = useSelector((state) => state.base);
  const { list: storeList } = useSelector((state) => state.store);
  useEffect(() => {
    if (!userInfo) {
      dispatch(setUserInfoAsync());
    }
    if (userInfo && !storeList) {
      dispatch(getStoreListAsync());
    }
  }, []);
  const isStore = useMemo(() => {
    if (!storeList) return false;
    return storeList.some((item) => {
      return +item.news.id === +params.id;
    });
  }, [storeList, params]);
  // 点击收藏按钮
  const handleStore = async () => {
    // 没有登录去登录
    if (!userInfo) {
      Toast.show({
        icon: "fail",
        content: "请先登录",
      });
      navigate(`/login?to=${location.pathname}`, { replace: true });
      return;
    }
    // 移除收藏
    if (isStore) {
      let item = storeList.find((item) => {
        return +item.news.id === +params.id;
      });
      if (!item) return;
      let { code } = await api.storeRemove(item.id);
      if (+code !== 0) {
        Toast.show({
          icon: "fail",
          content: "操作失败",
        });
        return;
      }
      Toast.show({
        icon: "success",
        content: "操作成功",
      });
      dispatch(removeStore(item.id));
      return;
    }
    // 收藏
    try {
      let { code } = await api.store(params.id);
      if (+code !== 0) {
        Toast.show({
          icon: "fail",
          content: "收藏失败",
        });
        return;
      }
      Toast.show({
        icon: "success",
        content: "收藏成功",
      });
      dispatch(getStoreListAsync());
    } catch (_) {}
  };
  return (
    <div className='detail-box'>
      {/* 新闻内容 */}
      {isFetching && <SkeletonAgain />}

      {isSuccess && (
        <div
          className='content'
          dangerouslySetInnerHTML={{
            __html: result.body,
          }}
        ></div>
      )}

      {/* 底部图标 */}
      <div className='tab-bar'>
        <div
          className='back'
          onClick={() => {
            navigate(-1);
          }}
        >
          <LeftOutline />
        </div>
        <div className='icons'>
          <Badge content={extraSuccess ? extraData.comments : 0}>
            <MessageOutline />
          </Badge>
          <Badge content={extraData ? extraData.popularity : 0}>
            <LikeOutline />
          </Badge>
          {/* 后面这两个是收藏和更多，用span好确定 */}
          <span className={isStore ? "stored" : ""} onClick={handleStore}>
            <StarOutline />
          </span>
          <span>
            <MoreOutline />
          </span>
        </div>
      </div>
    </div>
  );
}
